import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import whiteList from '@/common/config/whiteList';
import { useStore as useUserStore } from '@/store/user';
import { useStore as usePermissionStore } from "@/store/permission";
import { useStore as useTagsStore } from "@/store/tags";
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();
  if (userStore.info.token) {
    // 有token
    if (to.path === '/login') {
      next({ path: '/' });
    } else if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (userStore.info.roles.length === 0) {
        const [GetInfoErr, GetInfoRes] = await userStore.GetInfo();
        if (!GetInfoErr) {
          if (!permissionStore.state.pulled) {
            const accessRoutes = await permissionStore.GenerateRoutes();
            accessRoutes.forEach(x => {
              router.addRoute(x);
            })
          }
          if (!permissionStore.state.pulled) {
            next({ ...to, replace: true });
            permissionStore.state.pulled = true;
          } else {
            next();
          }
        } else {
          userStore.logout();
        }
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`); // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  NProgress.done();
  const tagsStore = useTagsStore();
  const { name, query, params, meta } = to;
  if (!to.meta?.affix) {
    tagsStore.addTag({
      name,
      query,
      params,
      meta,
    });
  } else {
    let idx = tagsStore?.tags?.findIndex?.(x => x.name === name);
    if (idx > -1) {
      tagsStore.tags[idx].meta = meta || {};
    }
  }
  tagsStore.tagChange(to);
  (document.title as any) = to.meta?.title || "海伦陪练后台管理中心";
})